import { parse } from 'querystring';
import _ from 'lodash';
/* eslint no-useless-escape:0 import/prefer-default-export:0 */

export const hasChildren = (list, item) => {
  let result = false;
  list.forEach(value => {
    if (value.pid === item.id) {
      result = true;
    }
  });
  return result;
};

export const buildTree = (list, pid = '0') => {
  const tree = [];
  list.forEach(value => {
    if (value.pid === pid) {
      if (hasChildren(list, value)) {
        value.children = [];
        value.children = buildTree(list, value.id);
      }
      tree.push(value);
    }
  });
  return tree;
};

export const buildChildren = (items, list, type) => {
  list.forEach(value => {
    if (value.type === type) {
      items.push(value);
    } else if (value.children && value.children.length) {
      buildChildren(items, value.children, type);
    }
  });
  return items;
};

export const getSearchItems = list => {
  const items = {};
  let types = [];
  // 筛选出所有类型
  _(list).forEach((value, index) => {
    types.push(value.type);
  });
  // 去重
  types = _.uniq(types);
  // 类型数组
  _(types).forEach(value => {
    items[value] = [];
  });
  // 遍历相同类型的对象插入数组
  _(list).forEach(value => {
    _(types).forEach(val => {
      if (val === value.type) {
        items[val].push(value);
      }
    });
  });

  return items;
};

export const getSearchTypeItems = (list = [], name, code) => {
  const data = [];
  _(list).forEach(value => {
    if (value[`${name}`] && value[`${code}`]) {
      data.push({
        name: value[`${name}`],
        code: value[`${code}`],
      });
    }
  });
  return _.uniqBy(data, 'name');
};

export const getSearchSeltetItems = (list, type, name, id) => {
  const items = [];
  const buildItems = buildChildren(items, list, type);
  return getSearchTypeItems(buildItems, name, id);
};

export const getExpandedRowKeys = list => {
  const expandedRowKeys = [];
  _.forEach(list, value => {
    expandedRowKeys.push(value.id);
  });
  return expandedRowKeys;
};
